package controller;

import beans.UploadedAlgorithmFile;
import dao.HistoryTaskDao;
import dao.JobDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class GetBlockState extends HttpServlet {

    private HistoryTaskDao historyTaskDao = new HistoryTaskDao();
    private JobDao jobDao = new JobDao();
    private static final long serialVersionUID = -6648802358677313526L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置最快返回时间不能低于5秒
        long start = System.currentTimeMillis();
        // 获取批任务hash
        String batchTaskHash = request.getParameter("taskHash");
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer waitTime = Integer.parseInt(request.getParameter("waitTime"));
        // 分页查询子任务信息，具体包括：subTaskHash(子任务hash)、statement(子任务状态)
        List<Object> subTaskHashes = historyTaskDao.getSubTaskHashStateByPage(batchTaskHash, onePageCount, currentPage);
        if(subTaskHashes.size()<1){
            response.getWriter().write("error");
        }else{
            int subTaskNum = historyTaskDao.getSubTaskNum(batchTaskHash);
            // 查询共有多少页
            int pageNum = historyTaskDao.getPageNum(batchTaskHash, onePageCount);
            // 查询批任务的子任务，计算任务完成率
            int taskFinishedNum = historyTaskDao.getTaskFinishedNum(batchTaskHash);
            float taskFinishedRatio = (float)taskFinishedNum/subTaskNum;
            // 查询批任务的算法，计算算法完成率
            JSONArray algorithmOrder = JSONArray.fromObject(historyTaskDao.getAlgorithmOrder(batchTaskHash));
            for(int i=0;i<algorithmOrder.size();i++){
                JSONObject algorithmObject = algorithmOrder.getJSONObject(i);
                String algorithmHash = (String) algorithmObject.get("blockId");
                int algFinishedNum = historyTaskDao.getAlgorithmFinishedNum(batchTaskHash, algorithmHash);
                algorithmObject.put("finishedRatio", (float)algFinishedNum/subTaskNum);
            }

            JSONArray resultArray = new JSONArray();
            // 查询每一个子任务详细情况
            for(Object one:subTaskHashes){
                JSONObject oneJsonObject = (JSONObject)one;
                // 获取子任务hash、状态
                String subTaskHash = oneJsonObject.getString("subTaskHash");
                String subTaskStatement = oneJsonObject.getString("statement");
                // 查询作业详情
                JSONArray jobSate = jobDao.getCompletedJobState(subTaskHash,false);
                JSONObject oneResult = new JSONObject();
                oneResult.put("taskHash", subTaskHash);
                oneResult.put("state", subTaskStatement);
                oneResult.put("detail", jobSate.toString());
                resultArray.add(oneResult);
            }
            JSONObject resultObject = new JSONObject();
            resultObject.put("result",resultArray);
            resultObject.put("pageNum",pageNum);
            resultObject.put("finishedRatio",taskFinishedRatio);
            resultObject.put("algorithmOrder",algorithmOrder);
            long end = System.currentTimeMillis();
            long queryTime = (end-start)/1000;
            // 当查询时间不足五秒时，等待至5秒后再返回
            if(queryTime<waitTime){
                try {
                    Thread.sleep((waitTime-queryTime)*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(taskFinishedRatio==1)
                UploadedAlgorithmFile.UPLOADED_ALGORITHM_FILE.cleanAlgorithmFileUri(batchTaskHash);
            response.getWriter().write(resultObject.toString());
        }
    }
}
